package com.wjh.rules.core.engine;

import com.wjh.rules.common.EngineResponse;
import com.wjh.rules.core.rule.RuleUnit;

import java.util.*;

/**
 * @ClassName DefaultLessRuleEngine
 * @Description:
 * @Author wjh
 * @Date 2020年6月19日
 */
public class DefaultLessRuleEngine extends AbstractLessRulesEngine {

    @Override
    public EngineResponse fire(Map<String, Object> fact) {
        Iterator<RuleUnit> it = this.ll.iterator();
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            RuleUnit ru = it.next();
            //单个规则器匹配
            boolean result = ru.fire(fact,ru);
            if (result) {
                String groupId = ru.getGroupId();
                String id = ru.getId();
                List<String> ruleIdList = resultMap.get(groupId);
                if (ruleIdList == null) {
                    ruleIdList = new ArrayList<String>();
                }
                ruleIdList.add(id);
                resultMap.put(groupId, ruleIdList);
                break;
            }
        }
        return this.assebleFireResult(resultMap);
    }

    @Override
    public EngineResponse fireFail(Map<String, Object> fact) {
        Iterator<RuleUnit> it = this.ll.iterator();
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            RuleUnit ru = it.next();
            //单个规则器匹配
            boolean result = ru.fire(fact,ru);
            if (!result) {
                String groupId = ru.getGroupId();
                String id = ru.getId();
                List<String> ruleIdList = resultMap.get(groupId);
                if (ruleIdList == null) {
                    ruleIdList = new ArrayList<String>();
                }
                ruleIdList.add(id);
                resultMap.put(groupId, ruleIdList);
                break;
            }
        }
        return this.assebleFireResult(resultMap);
    }


}
